{
 "cells": [
  {
   "cell_type": "raw",
   "id": "de9db017-6072-448e-9642-765c49c4aac9",
   "metadata": {
    "raw_mimetype": "text/restructuredtext"
   },
   "source": [
    ".. _nb_gradients:"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6e479c83-65fe-42fd-8006-31431882d22f",
   "metadata": {},
   "source": [
    "# Gradients"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1ed7c34d-09f1-4031-acdf-a327ba90a9eb",
   "metadata": {},
   "source": [
    "If the problem is implemented using autograd then the gradients through automatic differentiation are available out of the box. Let us consider the following problem definition for a simple quadratic function without any constraints:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5e480925-4e01-48dd-9316-3e48410c3ca6",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "import pymoo.gradient.toolbox as anp\n",
    "from pymoo.core.problem import Problem\n",
    "from pymoo.gradient.automatic import AutomaticDifferentiation\n",
    "\n",
    "\n",
    "class MyProblem(Problem):\n",
    "\n",
    "    def __init__(self):\n",
    "        super().__init__(n_var=10, n_obj=1, xl=-5, xu=5)\n",
    "\n",
    "    def _evaluate(self, x, out, *args, **kwargs):\n",
    "        out[\"F\"] = anp.sum(anp.power(x, 2), axis=1)\n",
    "\n",
    "problem = AutomaticDifferentiation(MyProblem())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b1d64428-553c-4d6a-967a-67114298261c",
   "metadata": {},
   "source": [
    "The gradients can be retrieved by appending `F` to the `return_values_of` parameter:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8e332e32-0d76-412d-aaaf-f4a24511f96a",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "X = np.array([np.arange(10)]).astype(float)\n",
    "F, dF = problem.evaluate(X, return_values_of=[\"F\", \"dF\"])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "169bc1c7-ada6-4378-a035-7a11924b7e26",
   "metadata": {},
   "source": [
    "The resulting gradients are stored in `dF` and the shape is (n_rows, n_objective, n_vars):"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8f137a00-2f29-4ef2-ba2e-a4f5b1aa3d84",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "print(X, F)\n",
    "print(dF.shape)\n",
    "print(dF)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "41e7650d-4460-43b8-b994-22bb05f2b621",
   "metadata": {},
   "source": [
    "Analogously, the gradient of constraints can be retrieved by appending `dG`."
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
